<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Constants\SyncTaskStatusConstants;
use App\CustHub\Model\ChSyncTask;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;

class ChSyncTaskMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChSyncTask::class;
    }

    public function findById(mixed $id): Collection|Model|array|ChSyncTask|Builder|null
    {
        return ChSyncTask::query()->find($id);
    }

    /**
     * 获取最新的分页参数
     * @param mixed $id
     * @param int $type
     * @param bool $isCorp
     * @return int|mixed
     */
    public function getLatestCurrentSeq(mixed $id,int $type,bool $isCorp = false): mixed
    {
        $syncTaskInfo = ChSyncTask::query()
            ->select(['id','extra'])
            ->where(function ($query) use ($id,$isCorp){
                if($isCorp){
                    $query->where('corp_id',$id);
                }else{
                    $query->where('robot_id',$id);
                }
            })
            ->where('type', $type)
            ->orderBy('created_at', 'desc')
            ->first();
        $currentSeq = 0;
        if(!empty($syncTaskInfo)){
            $extra = $syncTaskInfo->extra;
            $currentSeq =  $extra['current_seq'] ?? 0;
        }
        return $currentSeq;
    }

    /**
     * 检查是否正在进行中的任务
     * @param mixed $id
     * @param int $type
     * @param bool $isCorp
     * @return bool
     */
    public function checkIsTaskInProgress(mixed $id,int $type,bool $isCorp = false): bool
    {
        return $this->model::query()
            ->where(function ($query) use ($id,$isCorp){
                if($isCorp){
                    $query->where('corp_id',$id);
                }else{
                    $query->where('robot_id',$id);
                }
            })
            ->where('type',$type)
            ->whereIn('status',SyncTaskStatusConstants::getInProcessStatus())
            ->exists();
    }

}